<?php

$path = dirname(dirname(__FILE__));
require($path.'/lib/crt.php');
require($path.'/lib/block.php');
$crt = new CRT();
$crt->init();

$op = Clean::string($_REQUEST['op'],false, false, true);

switch($op) {
	case 'rejectEdit' :
		$id = Clean::int($_REQUEST['id'], false, true);
		$hqId = Clean::int($_REQUEST['hqId']);
		CRTBlock::rejectPending($id);

		$pending = CRTBlock::getPending($hqId);
		echo json_encode($pending);
		break;

	case 'getPending' :

		$id = Clean::int($_REQUEST['id'], false, true);

		if($id) {
			$pending = CRTBlock::getPending($id);
			echo json_encode($pending);
		
		}

		break;

	case 'applyChanges' : 
		$nhId = Clean::int($_REQUEST['nhId']);
		$hqId = Clean::int($_REQUEST['hqId']);

		if($nhId && $hqId) {
			require_once($path.'/lib/block.php');

			$db = DBs::getGISDB();
			$sql = "SELECT name FROM ".PENDING_TBL."  WHERE id=$nhId";
			$name = $db->GetOne($sql);

			CRTBlock::updateBlocks(array($hqId), $name);
			CRTBlock::clearPending($hqId);
			echo json_encode($name);
		}
		
		break;
	case 'applyAllEdits' :
		$db = DBs::getGISDB();
		$sql = "SELECT DISTINCT blockId FROM ".PENDING_TBL;
		$blocks = $db->GetCol($sql);

		foreach($blocks as $b) {
			$sql = "select  top 1 blockId, name, count(name) as nhCount from ". PENDING_TBL. "
				 where blockId=$b group by blockId, name order by nhCount DESC";
			$nh = $db->GetRow($sql);
			CRTBlock::updateBlocks(array($b), $nh['name']);
			CRTBlock::clearPending($b);

		}

		echo json_encode(true);

		//$sq
		break;

	case 'rejectAllEdits' :
		$db = DBs::getGISDB();
                $sql = "DELETE FROM ".PENDING_TBL;
		$db->_Execute($sql);

		echo json_encode(true);

		break;

	default :
		exit;

	
}

?>
